import axios from 'axios'

console.log('加载API模块...')

// 创建 axios 实例
const api = axios.create({
  baseURL: 'http://localhost:5000', // 直接使用后端完整URL
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json'
  },
  withCredentials: false // 跨域请求不发送cookies
})

// 处理静态资源URL的函数
export const getFullStaticUrl = (url: string) => {
  if (!url) return '';
  
  // 如果URL已经是完整URL（以http开头），则直接返回
  if (url.startsWith('http')) {
    return url;
  }
  
  // 将路径中的反斜杠替换为正斜杠
  let normalizedUrl = url.replace(/\\/g, '/');
  
  // 直接使用完整的后端URL
  return `http://localhost:5000${normalizedUrl.startsWith('/') ? normalizedUrl : '/' + normalizedUrl}`;
};

// 测试后端连通性
fetch('http://localhost:5000/api/status')
  .then(response => response.json())
  .then(data => {
    console.log('✅ 后端连通性测试成功:', data)
  })
  .catch(error => {
    console.error('❌ 后端连通性测试失败:', error)
  })

// 拦截请求
api.interceptors.request.use(
  config => {
    console.log('📤 发送请求:', config.method?.toUpperCase(), config.url, config.data || config.params)
    return config
  },
  error => {
    console.error('❌ 请求错误:', error)
    return Promise.reject(error)
  }
)

// 拦截响应
api.interceptors.response.use(
  response => {
    console.log('📥 收到响应:', response.status, response.data)
    return response
  },
  error => {
    console.error('❌ 响应错误:', error.message)
    if (error.response) {
      console.error('错误状态码:', error.response.status)
      console.error('错误数据:', error.response.data)
    } else if (error.request) {
      console.error('未收到响应，请求详情:', error.request)
    }
    return Promise.reject(error)
  }
)

// 后端API响应类型定义
interface StatusResponse {
  status: string
  version: string
  models: string[]
  server_time: string
}

interface UploadResponse {
  message: string
  original_filename: string
  file_size: number
  preprocessed_image_url: string
  preprocessed_image_path: string
}

interface DetectionResult {
  type: string
  class?: string
  confidence: number
  bbox: [number, number, number, number]
}

interface VehicleDetectionResponse {
  message: string
  marked_image_url: string
  detection_results: DetectionResult[]
  overall_accuracy: number
  detection_count: number
}

interface LicensePlateResponse {
  message: string
  marked_image_url: string
  cropped_plate_url: string
  detection_results: DetectionResult[]
  overall_accuracy: number
  detection_count: number
}

// 多辆车检测响应类型
interface MultiVehicleDetectionResponse {
  message: string
  marked_image_url: string
  detection_results: DetectionResult[]
  overall_accuracy: number
  detection_count: number
}

interface OCRRecognitionResponse {
  message: string
  plate_text: string
  ocr_confidence: number
  ocr_res_img_url: string
}

interface FullProcessResponse {
  message: string
  vehicle_detection: {
    marked_image_url: string
    detection_results: DetectionResult[]
    accuracy: number
    detection_count: number
  }
  license_plate_recognition: {
    marked_image_url: string
    cropped_plate_url: string
    detection_results: DetectionResult[]
    accuracy: number
    detection_count: number
  }
  overall_accuracy: number
}

// 车辆-车牌联合检测响应类型
interface VehiclePlateJointResponse {
  marked_image_url: string
  message: string
  overall_accuracy: number
  plate_accuracy: number
  vehicle_accuracy: number
  plate_count: number
  vehicle_count: number
  plate_text: string
  plate_detections: Array<{
    bbox: [number, number, number, number]
    confidence: number
    ocr_confidence: number
    plate_text: string
    type: string
  }>
  vehicle_detections: Array<{
    bbox: [number, number, number, number]
    class: string
    confidence: number
    type: string
  }>
}

// 前端使用的检测结果类型
export interface FrontendDetectionResult {
  marked_image_url: string
  license_plate_text?: string
  confidence?: number | null
  model_runtime?: number | null
  vehicle_count?: number | null
  plates?: Array<{
    text: string
    confidence: number
  }> | null
  overall_accuracy: number | null
  detection_results?: DetectionResult[] | null
  model_name?: string
  detection_time?: string
  cropped_plate_url?: string
  vehicle_marked_image_url?: string
  ocr_plate_text?: string
  ocr_confidence?: number
  ocr_res_img_url?: string
  // 新增联合检测结果字段
  plate_accuracy?: number
  vehicle_accuracy?: number
  plate_count?: number
  plate_detections?: Array<{
    bbox: [number, number, number, number]
    confidence: number
    ocr_confidence: number
    plate_text: string
    type: string
  }>
  vehicle_detections?: Array<{
    bbox: [number, number, number, number]
    class: string
    confidence: number
    type: string
  }>
}

/**
 * 获取系统状态
 * @returns Promise 包含系统状态信息
 */
export const getSystemStatus = async (): Promise<StatusResponse> => {
  try {
    const response = await api.get<StatusResponse>('/api/status')
    return response.data
  } catch (error) {
    console.error('❌ 获取系统状态错误:', error)
    throw error
  }
}

/**
 * 上传图片
 * @param file 原始图片文件
 * @returns Promise 包含预处理后的图片信息
 */
export const uploadAndPreprocessImage = async (file: File): Promise<UploadResponse> => {
  const formData = new FormData()
  formData.append('image', file)

  try {
    console.log('🚀 开始上传图片...', file.name, file.size)
    
    const response = await api.post<UploadResponse>('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    console.log('✅ 上传图片响应:', response.data)
    
    // 处理静态资源URL
    const data = response.data;
    if (data.preprocessed_image_url) {
      data.preprocessed_image_url = getFullStaticUrl(data.preprocessed_image_url);
    }
    
    return data;
  } catch (error: any) {
    console.error('❌ 上传图片错误:', error)
    if (error.response) {
      console.error('错误状态:', error.response.status)
      console.error('错误数据:', error.response.data)
    } else if (error.request) {
      console.error('未收到响应，可能是网络问题或CORS问题')
    }
    throw error
  }
}

/**
 * 车辆检测
 * @param preprocessed_image_path 预处理后的图片路径
 * @returns Promise 包含车辆检测结果
 */
export const detectVehicle = async (preprocessed_image_path: string): Promise<VehicleDetectionResponse> => {
  try {
    console.log('🚀 开始车辆检测，图片路径:', preprocessed_image_path)
    
    const response = await api.post<VehicleDetectionResponse>('/api/vehicle_detection', {
      preprocessed_image_path
    })
    
    console.log('✅ 车辆检测响应:', response.data)
    
    // 处理静态资源URL
    const data = response.data;
    if (data.marked_image_url) {
      data.marked_image_url = getFullStaticUrl(data.marked_image_url);
    }
    
    return data;
  } catch (error: any) {
    console.error('❌ 车辆检测错误:', error)
    throw error
  }
}

/**
 * 车牌检测
 * @param preprocessed_image_path 预处理后的图片路径
 * @returns Promise 包含车牌检测结果
 */
export const detectLicensePlate = async (preprocessed_image_path: string): Promise<LicensePlateResponse> => {
  try {
    console.log('🚀 开始车牌检测，图片路径:', preprocessed_image_path)
    
    const response = await api.post<LicensePlateResponse>('/api/license_plate_recognition', {
      preprocessed_image_path
    })
    
    console.log('✅ 车牌检测响应:', response.data)
    
    // 处理静态资源URL
    const data = response.data;
    if (data.marked_image_url) {
      data.marked_image_url = getFullStaticUrl(data.marked_image_url);
    }
    if (data.cropped_plate_url) {
      data.cropped_plate_url = getFullStaticUrl(data.cropped_plate_url);
    }
    
    return data;
  } catch (error: any) {
    console.error('❌ 车牌检测错误:', error)
    throw error
  }
}

/**
 * 完整处理流程
 * @param preprocessed_image_path 预处理后的图片路径
 * @returns Promise 包含完整的处理结果
 */
export const fullProcess = async (preprocessed_image_path: string): Promise<FullProcessResponse> => {
  try {
    console.log('🚀 开始完整处理流程，图片路径:', preprocessed_image_path)
    
    const response = await api.post<FullProcessResponse>('/api/full_process', {
      preprocessed_image_path
    })
    
    console.log('✅ 完整处理响应:', response.data)
    
    // 处理静态资源URL
    const data = response.data;
    if (data.vehicle_detection.marked_image_url) {
      data.vehicle_detection.marked_image_url = getFullStaticUrl(data.vehicle_detection.marked_image_url);
    }
    if (data.license_plate_recognition.marked_image_url) {
      data.license_plate_recognition.marked_image_url = getFullStaticUrl(data.license_plate_recognition.marked_image_url);
    }
    if (data.license_plate_recognition.cropped_plate_url) {
      data.license_plate_recognition.cropped_plate_url = getFullStaticUrl(data.license_plate_recognition.cropped_plate_url);
    }
    
    return data;
  } catch (error: any) {
    console.error('❌ 完整处理错误:', error)
    throw error
  }
}

/**
 * 车辆-车牌联合检测
 * @param preprocessed_image_path 预处理后的图片路径
 * @returns Promise 包含联合检测结果
 */
export const detectVehiclePlateJoint = async (preprocessed_image_path: string): Promise<VehiclePlateJointResponse> => {
  try {
    console.log('🚀 开始车辆-车牌联合检测，图片路径:', preprocessed_image_path)
    
    const response = await api.post<VehiclePlateJointResponse>('/api/vehicle_plate_detection', {
      preprocessed_image_path
    })
    
    console.log('✅ 车辆-车牌联合检测响应:', response.data)
    
    // 处理静态资源URL
    const data = response.data;
    if (data.marked_image_url) {
      data.marked_image_url = getFullStaticUrl(data.marked_image_url);
    }
    
    return data;
  } catch (error: any) {
    console.error('❌ 车辆-车牌联合检测错误:', error)
    throw error
  }
}

/**
 * 多辆车检测
 * @param preprocessed_image_path 预处理后的图片路径
 * @returns Promise 包含多辆车检测结果
 */
export const detectMultiVehicle = async (preprocessed_image_path: string): Promise<MultiVehicleDetectionResponse> => {
  try {
    console.log('🚀 开始多辆车检测，图片路径:', preprocessed_image_path)
    
    const response = await api.post<MultiVehicleDetectionResponse>('/api/multi_vehicle_detection', {
      preprocessed_image_path
    })
    
    console.log('✅ 多辆车检测响应:', response.data)
    
    // 处理静态资源URL
    const data = response.data;
    if (data.marked_image_url) {
      data.marked_image_url = getFullStaticUrl(data.marked_image_url);
    }
    
    return data;
  } catch (error: any) {
    console.error('❌ 多辆车检测错误:', error)
    throw error
  }
}

/**
 * 根据选择的模型类型进行检测
 * @param preprocessedImagePath 预处理后的图片路径
 * @param modelType 模型类型
 * @returns Promise 包含标注后的图片URL和识别到的结果
 */
export const detectAndRecognizeImage = async (
  preprocessedImagePath: string,
  modelType: 'model_a' | 'model_b' | 'model_c' | 'model_d' = 'model_b'
): Promise<FrontendDetectionResult> => {
  try {
    // 处理URL，确保传递给后端的是相对路径
    let apiImagePath = preprocessedImagePath;
    if (apiImagePath.startsWith('http://localhost:5000')) {
      apiImagePath = apiImagePath.replace('http://localhost:5000', '');
    }
    
    console.log('🚀 开始检测识别，参数:', { preprocessed_image_path: apiImagePath, modelType })
    
    // 根据模型类型调用不同的API
    if (modelType === 'model_a') {
      // 车辆检测模型
      const vehicleData = await detectVehicle(apiImagePath);
      
      return {
        marked_image_url: vehicleData.marked_image_url,
        detection_results: vehicleData.detection_results,
        overall_accuracy: vehicleData.overall_accuracy,
        vehicle_count: vehicleData.detection_count,
        model_name: '车辆检测模型',
        detection_time: new Date().toLocaleString()
      };
    } else if (modelType === 'model_c') {
      // 车辆-车牌联合检测模型
      const jointData = await detectVehiclePlateJoint(apiImagePath);
      
      return {
        marked_image_url: jointData.marked_image_url,
        license_plate_text: jointData.plate_text,
        overall_accuracy: jointData.overall_accuracy,
        vehicle_count: jointData.vehicle_count,
        plate_count: jointData.plate_count,
        plate_accuracy: jointData.plate_accuracy,
        vehicle_accuracy: jointData.vehicle_accuracy,
        plate_detections: jointData.plate_detections,
        vehicle_detections: jointData.vehicle_detections,
        model_name: '车辆-车牌联合检测模型',
        detection_time: new Date().toLocaleString()
      };
    } else if (modelType === 'model_d') {
      // 多辆车检测模型
      const multiVehicleData = await detectMultiVehicle(apiImagePath);
      
      return {
        marked_image_url: multiVehicleData.marked_image_url,
        detection_results: multiVehicleData.detection_results,
        overall_accuracy: multiVehicleData.overall_accuracy,
        vehicle_count: multiVehicleData.detection_count,
        model_name: '多辆车检测模型',
        detection_time: new Date().toLocaleString()
      };
    } else {
      // 完整处理流程（车辆 + 车牌）
      const fullData = await fullProcess(apiImagePath);
      
      // 提取车牌信息
      const plateResults = fullData.license_plate_recognition.detection_results;
      const plateConfidence = plateResults.length > 0 ? plateResults[0].confidence : null;
      
      return {
        // 车牌检测图片
        marked_image_url: fullData.license_plate_recognition.marked_image_url,
        // 车辆检测图片
        vehicle_marked_image_url: fullData.vehicle_detection.marked_image_url,
        // 切割车牌图片
        cropped_plate_url: fullData.license_plate_recognition.cropped_plate_url,
        license_plate_text: plateResults.length > 0 ? `检测到${plateResults.length}个车牌` : '未识别车牌',
        confidence: plateConfidence,
        vehicle_count: fullData.vehicle_detection.detection_count,
        detection_results: [
          ...fullData.vehicle_detection.detection_results,
          ...fullData.license_plate_recognition.detection_results
        ],
        overall_accuracy: fullData.overall_accuracy,
        model_name: '车辆与车牌检测模型',
        detection_time: new Date().toLocaleString()
      };
    }
  } catch (error: any) {
    console.error('❌ 检测识别错误:', error)
    throw error
  }
}

/**
 * 车牌OCR识别
 * @param cropped_plate_path 切割后的车牌图片路径
 * @returns Promise 包含OCR识别结果
 */
export const ocrRecognition = async (cropped_plate_path: string): Promise<OCRRecognitionResponse> => {
  try {
    console.log('🚀 开始OCR识别，车牌图片路径:', cropped_plate_path)
    
    const response = await api.post<OCRRecognitionResponse>('/api/ocr_recognition', {
      cropped_plate_path
    })
    
    console.log('✅ OCR识别响应:', response.data)
    
    // 处理静态资源URL
    const data = response.data;
    if (data.ocr_res_img_url) {
      // 确保OCR结果图片URL格式正确
      // 后端返回的路径可能是相对于static目录的，需要转换为完整URL
      if (data.ocr_res_img_url.startsWith('/static/')) {
        data.ocr_res_img_url = getFullStaticUrl(data.ocr_res_img_url);
      } else {
        // 如果路径不是以/static/开头，可能是其他格式，也需要转换为完整URL
        data.ocr_res_img_url = getFullStaticUrl(data.ocr_res_img_url);
      }
    }
    
    return data;
  } catch (error: any) {
    console.error('❌ OCR识别错误:', error)
    throw error
  }
}

console.log('API模块加载完成')

export default api 